package com.lagou.work02.dao.impl;

import com.lagou.work02.dao.AccountDao;
import com.lagou.work02.pojo.MoneyInfo;
import com.lagou.work02.stereotype.MyAutowired;
import com.lagou.work02.stereotype.MyService;
import com.lagou.work02.util.ConnectionUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@MyService("accountDao")
public class AccountDaoImpl implements AccountDao {

    private ConnectionUtils connectionUtils;

    @MyAutowired
    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    @Override
    public MoneyInfo findByName(String name) throws Exception {
        Connection connection = connectionUtils.getCurrentThreadConn();
        String sql = "select * from money_info where name = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,name);
        ResultSet resultSet = preparedStatement.executeQuery();

        MoneyInfo moneyInfo = new MoneyInfo();

        if (resultSet.next()) {
            moneyInfo.setName(resultSet.getString("name"));
            moneyInfo.setMoney(resultSet.getInt("money"));
        }
        resultSet.close();
        preparedStatement.close();
//        connection.close();
        return moneyInfo;
    }

    @Override
    public int updateMoneyByName(String name, int money) throws Exception {
        Connection connection = connectionUtils.getCurrentThreadConn();
        String sql = "update money_info set money = ? where name = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1, money);
        preparedStatement.setString(2,name);
        int i = preparedStatement.executeUpdate();
        preparedStatement.close();
//        connection.close();
        return i;
    }
}
